<template>
  <el-card class="layout-query">
    <div style="max-width: 50%;margin: 2%">
      <el-steps style="max-width: 100%" :active="active" align-center>
        <el-step title="创建作业基本信息" description="填写作业的信息" />
        <el-step title="创建作业题目" description="填写作业的题目" />
      </el-steps>
    </div>
  </el-card>

  <!-- 第一步-创建作业基本信息 -->
  <el-card v-if="active === 1">
    <el-space style="margin-bottom: 2%;">
      <el-space>
        <el-button style="margin-top: 12px" @click="next">下一步</el-button>
      </el-space>
    </el-space>
    <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" :label-width="300">
      <el-form-item label="作业名称" prop="taskName">
        <el-input v-model="dataForm.taskName" placeholder="作业名称" style="max-width: 50%;"></el-input>
      </el-form-item>
      <el-form-item label="作业开始时间" prop="startTime">
        <el-date-picker
  v-model="dataForm.startTime"
  type="datetime"
  placeholder="请选择作业开始时间"
  format="YYYY-MM-DD HH:mm:ss"
  value-format="YYYY-MM-DD HH:mm:ss"
  date-format="MMM DD, YYYY"
  time-format="HH:mm"
/>
      </el-form-item>
      <el-form-item label="作业结束时间" prop="endTime">
       <el-date-picker
  v-model="dataForm.endTime"
  type="datetime"
  placeholder="请选择作业结束时间"
  format="YYYY-MM-DD HH:mm:ss"
  value-format="YYYY-MM-DD HH:mm:ss"
  date-format="MMM DD, YYYY"
  time-format="HH:mm"
/>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 第二步-创建作业题目 -->
  <el-card v-if="active === 2">
    <el-space style="margin-bottom: 2%;">
      <el-space>
        <el-button style="margin-top: 12px" @click="prev">返回上一步</el-button>
        <el-button style="margin-top: 12px" @click="topicDBSwitch = true">从题库添加题目</el-button>
        <el-button style="margin-top: 12px" @click="handleAddCustomTopic">添加自定义题目</el-button>
        <el-button type="primary" style="margin-top: 12px" @click="createTask()">创建作业</el-button>
      </el-space>
    </el-space>
    <!-- 题目列表,一行展示三题 -->
    <el-row :gutter="20">
      <el-col v-for="(topic, index) in dataForm.topicList" :key="index" :span="8">
        <el-card style="margin-bottom: 20px" shadow="hover">
          <template #header>
            <el-text>题目:{{ topic.topicOrder }}</el-text> <!-- 改为使用topicOrder -->
            <el-text style="margin-left: 20%;">题目名称:{{ topic.topicName }}</el-text>
          </template>
          <el-text type="info">题目类型：{{ getTopicTypeLabel(topic.topicType) }}</el-text>
          <template #footer>
            <el-button type="success" @click="handleEditTopic(index)">查看题目详情</el-button>
            <el-button type="danger" @click="removeTopic(index)">移除题目</el-button>
          </template>
        </el-card>
      </el-col>
    </el-row>
  </el-card>

  <!-- 题库抽屉 -->
  <el-drawer v-model="topicDBSwitch" size="40%">
    <template #header>
      <el-text class="mx-1" size="large" type="primary">题库中心</el-text>
    </template>
    <template #default>
      <div>
        <!-- 题库内容可根据实际需求补充 -->
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick()">确认添加题目</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 题目详情弹窗 -->
  <el-dialog v-model="topicDetailSet" :title="`题目【${editIndex === -1 ? dataForm.topicList.length + 1 : editIndex + 1}】`" width="60%" center>
    <el-card style="max-width: 100%">
      <template #header>
        <span>题目名称：</span>
        <el-input v-model="currentTopic.topicName" style="width: 250px" placeholder="请输入题目名称" clearable />
        <span style="margin-left: 5%;">题目类型：</span>
        <el-select v-model="currentTopic.topicType" clearable placeholder="请选择题目类型" style="width: 240px;">
          <el-option v-for="item in topicTypeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </template>
      <!-- 根据题目类型展示不同详情 -->
       <!-- 论述题 -->
       <el-card v-if="currentTopic.topicType === '0'">
      <el-button color="#626aef" style="display: block; width: 100%;margin-bottom: 0px;" plain disabled>题目详情</el-button>
      <el-input v-model="currentTopic.topicDetail" style="display: block;" :autosize="{ minRows: 2, maxRows: 4 }"
        type="textarea" placeholder="请输入题目详情" />
      <template #footer>
        <el-button color="#626aef" style="display: block; width: 100%;margin-bottom: 0px;" plain disabled>答案详情</el-button>
        <el-input v-model="currentTopic.answerDetail" style="display: block;" :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea" placeholder="请输入答案详情" />
      </template>
       </el-card>

<!-- 在题目详情弹窗中修改文件题部分 -->
<el-card v-if="currentTopic.topicType === '4'">
  <el-button color="#626aef" style="display: block; width: 100%;margin-bottom: 0px;" plain disabled>题目详情</el-button>
  <el-input v-model="currentTopic.topicDetail" style="display: block;" :autosize="{ minRows: 2, maxRows: 4 }"
           type="textarea" placeholder="请输入题目详情" />
  <template #footer>
    <el-button color="#626aef" style="display: block; width: 100%;margin-bottom: 0px;" plain disabled>答案上传</el-button>
    <!-- 使用自定义文件上传组件 -->
    <MaUploadFile v-model="currentTopic.answerDetailFileList" />
  </template>
</el-card>
      
      
    </el-card>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="topicDetailSet = false">关闭</el-button>
        <el-button type="primary" @click="saveTopic">
          保存{{ editIndex === -1 ? '' : '修改' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive ,onMounted} from 'vue'
import { useRoute ,useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'
import type { SysFileUploadVO } from '@/api/sys/upload';
import { useSmTaskApi, useSmTaskSubmitApi } from '@/api/sm/task'
// 获取作业数据
const router = useRouter()
const route = useRoute();
const courseUserId = route.query.courseUserId;

// 步骤控制
const active = ref(1)
// 表单校验规则
const dataRules = ref({
  taskName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})
// 题目类型列表
const topicTypeList = [
{ value: '0', label: '论述题' },
{ value: '1', label: '单选题' },
{ value: '2', label: '多选题' },
{ value: '3', label: '判断题' },
{ value: '4', label: '文件题' },
]

// 题库抽屉开关
const topicDBSwitch = ref(false)
// 题目详情弹窗
const topicDetailSet = ref(false)
// 当前编辑题目的索引（-1表示新增）
const editIndex = ref(-1)
// 修改currentTopic结构
const currentTopic = reactive({
  id: undefined as string | undefined,
  sourceType: 0, // 0-自定义题目 1-题库题目
  topicOrder: 0,  // 新增序号字段
  topicId: '',  // 新增题目ID
  answerId: '', // 新增答案ID
  topicName: '',
  topicType: '',
  topicDetail: '',
  answerDetail: '',
  answerDetailFileList: [] as SysFileUploadVO[] // 修改为文件对象数组
})

// 作业表单数据
const dataForm = reactive({
id: undefined as string | undefined,
courseUserId: courseUserId,
taskName: '',
startTime: '',
endTime: '',
topicList: [] as Array<{
  id?: string
  topicOrder: number  // 新增序号字段
  topicName: string
  topicType: string
  topicDetail: string
  sourceType: number
  topicId: string
  answerId: string
  answerDetail: string
  answerDetailFileList: SysFileUploadVO[]  // 新增字段
}>
})

// 修改初始化代码中的map方法
onMounted(async () => {
  const taskId = route.query.taskId as string
  if (taskId) {
    try {
      const { data } = await useSmTaskApi(taskId)
      Object.assign(dataForm, {
        id: taskId,
        courseUserId: data.courseUserId,
        taskName: data.taskName,
        startTime: data.startTime,
        endTime: data.endTime,
        topicList: data.topicList.map((t: any, index: number) => ({ // 修复参数位置
          id: t.id,
          sourceType: t.sourceType || '0', // 默认设为自定义题目
          topicId: t.topicId || '',      // 新增字段映射
          answerId: t.answerId || '',   // 新增字段映射
          topicOrder: t.topicOrder || index + 1, // 正确使用index
          topicName: t.topicName,
          topicType: t.topicType,
          topicDetail: t.topicDetail,
          answerDetail: t.answerDetail,
          answerDetailFileList: t.answerDetailFileList?.map(f => ({
            id: f.id.toString(),
            name: f.name,
            url: f.url
          })) || []
        }))
      })
      active.value = 1 
    } catch (e) {
      ElMessage.error('获取作业详情失败')
    }
  }
})

// 获取题目类型标签
const getTopicTypeLabel = (value: string) => {
return topicTypeList.find(item => item.value === value)?.label || '未知类型'
}

// 新增题目
const handleAddCustomTopic = () => {
  editIndex.value = -1
  Object.assign(currentTopic, {
    id: undefined,
    sourceType: '0', // 设置为自定义题目
    topicOrder: dataForm.topicList.length + 1, // 自动生成新序号
    topicName: '',
    topicType: '',
    topicDetail: '',
    answerDetail: '',
    answerDetailFileList: []
  })
  topicDetailSet.value = true
}

// 编辑题目
const handleEditTopic = (index: number) => {
  editIndex.value = index
  const topic = dataForm.topicList[index]
  Object.assign(currentTopic, {
    id: topic.id,
    topicId: topic.topicId,      // 新增字段
    answerId: topic.answerId,    // 新增字段
    topicOrder: topic.topicOrder,  // 保持原有顺序
    sourceType: topic.sourceType,
    topicName: topic.topicName,
    topicType: topic.topicType,
    topicDetail: topic.topicDetail,
    answerDetail: topic.answerDetail,
    answerDetailFileList: [...topic.answerDetailFileList]
  })
  topicDetailSet.value = true
}

// 保存题目
const saveTopic = () => {
  if (!currentTopic.topicName) {
    ElMessage.warning('请输入题目名称')
    return
  }
  if (!currentTopic.topicType) {
    ElMessage.warning('请选择题目类型')
    return
  }

  // 题目类型校验
  if (currentTopic.topicType === '0' && !currentTopic.answerDetail) {
    ElMessage.warning('请输入答案详情')
    return
  }
  if (currentTopic.topicType === '4' && currentTopic.answerDetailFileList.length === 0) {
    ElMessage.warning('请上传至少一个文件')
    return
  }

  const newTopic = {
    id: currentTopic.id,
    topicId: currentTopic.topicId,    // 新增字段
    answerId: currentTopic.answerId,  // 新增字段
    topicOrder: currentTopic.topicOrder,  // 携带顺序字段
    sourceType: currentTopic.sourceType,
    topicName: currentTopic.topicName,
    topicType: currentTopic.topicType,
    topicDetail: currentTopic.topicDetail,
    answerDetail: currentTopic.topicType === '0' ? currentTopic.answerDetail : '',
    answerDetailFileList: currentTopic.topicType === '4' ? [...currentTopic.answerDetailFileList] : []
  }

  if (editIndex.value === -1) {
    dataForm.topicList.push(newTopic)
  } else {
    dataForm.topicList.splice(editIndex.value, 1, newTopic)
  }
  
  topicDetailSet.value = false
  ElMessage.success(editIndex.value === -1 ? '题目添加成功' : '题目修改成功')
  dataForm.topicList.sort((a, b) => a.topicOrder - b.topicOrder)
}

// 移除题目
const removeTopic = (index: number) => {
  ElMessageBox.confirm('确定要移除该题目吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    dataForm.topicList.splice(index, 1)
    // 重新计算序号（如果需要连续序号）
    dataForm.topicList.forEach((topic, idx) => {
      topic.topicOrder = idx + 1
    })
    ElMessage.success('题目移除成功')
  })
}

// 提交作业
const createTask = async () => {
  try {
    // 作业题目必须大于零否则无法创建
    if (dataForm.topicList.length === 0) {
      ElMessage.warning('请添加题目')
      return
    }
    const payload = {
      ...dataForm,
      topicList: dataForm.topicList.map(topic => ({
        id: topic.id,
        sourceType: topic.sourceType,
        topicId: topic.topicId,      // 新增字段
        answerId: topic.answerId,    // 新增字段
        topicOrder: topic.topicOrder,  // 提交顺序字段
        topicName: topic.topicName,
        topicType: topic.topicType,
        topicDetail: topic.topicDetail,
        answerDetail: topic.answerDetail,
        answerDetailFileList: topic.answerDetailFileList
      }))
    }

    await useSmTaskSubmitApi(payload)
    ElMessage.success(dataForm.id ? '作业更新成功' : '作业创建成功')
    router.back()
  } catch (e) {
    console.error("创建作业失败")
  }
}

// 取消按钮
const cancelClick = () => {
topicDBSwitch.value = false
}

// 添加题库题目（示例方法）
const confirmClick = () => {
ElMessage({
  message: '添加题目成功',
  grouping: true,
  type: 'success'
})
sourceType: 1 // 设为题库题目
topicDBSwitch.value = false
}

// 步骤切换
const next = () => {
if (active.value++ > 2) active.value = 0
}
const prev = () => {
if (active.value > 0) {
  active.value--;
}
}
</script>

<style scoped>
.el-col {
margin-bottom: 20px;
}
.el-card__header {
display: flex;
justify-content: space-between;
align-items: center;
}
</style>